package org.formal.system.shiro.manager;

import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;
import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;

/**
 * AES加解密
 *
 */
public class AESUtils {

    /**
     * 密钥算法
     */
    private static final String ALGORITHM = "AES";

    /**
     * SecretKeySpec类是KeySpec接口的实现类,用于构建秘密密钥规范
     */
    private static String sKey = "#/QW?ERO?ASD?GHL";

    /**
     * 加解密算法/工作模式/填充方式
     */
    private static final String ALGORITHM_STR = "AES/ECB/PKCS5Padding";

    private static SecretKeySpec key = new SecretKeySpec(sKey.getBytes(), ALGORITHM);

    /**
     * AES加密
     * @param data
     * @return
     * @throws Exception
     */
    public static String encryptData(String data) throws Exception {
        Cipher cipher = Cipher.getInstance(ALGORITHM_STR);
        cipher.init(Cipher.ENCRYPT_MODE, key);
        return new BASE64Encoder().encode(cipher.doFinal(data.getBytes()));
    }

    /**
     * AES解密
     * @param base64Data
     * @return
     * @throws Exception
     */
    public static String decryptData(String base64Data) {
        try {
            Cipher cipher = Cipher.getInstance(ALGORITHM_STR);
            cipher.init(Cipher.DECRYPT_MODE, key);
            return new String(cipher.doFinal(new BASE64Decoder().decodeBuffer(base64Data)));
        } catch (Exception e) {
            System.out.println("解密失败");
        }
        return null;
    }

    public static void main(String[] args) throws Exception {
        System.out.println("cardNo:"+AESUtils.encryptData("1"));
        System.out.println("exp:"+AESUtils.decryptData("e8c7bdeac83507f6f9d7ae86e2cdacbd"));
    }
}

